package com.example.pharmacy.service;

import com.example.pharmacy.mapper.*;
import com.example.pharmacy.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: asus
 * Date: 2024-12-25
 * Time: 17:20
 */
@Service
public class CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private DrugInfoMapper drugInfoMapper;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private OrderItemService orderItemService;
    public Integer addDrug(Cart cart) {

        return cartMapper.addDrug(cart);
    }
    public List<CartResult> getDrugList(Integer userId) {
        List<Cart> carts = cartMapper.selectCartByUserId(userId);
        List<CartResult> cartResults = new ArrayList<>();
        for (Cart cart : carts) {
            CartResult cartResult = new CartResult();
            DrugInfo drugInfo = drugInfoMapper.selectDrugById(cart.getDrugId());
            cartResult.setPicture(drugInfo.getPicture());
            cartResult.setCartId(cart.getCartId());
            cartResult.setDrugName(drugInfo.getDrugName());
            BigDecimal price = drugInfo.getPrice();
            cartResult.setPrice(price);
            BigDecimal num = new BigDecimal(cart.getNum());
            cartResult.setNum(cart.getNum());
            BigDecimal sum = price.multiply(num);
            cartResult.setSumPrice(sum);

            cartResults.add(cartResult);
        }
        return cartResults;
    }
    public Integer updateCart(Cart cart) {
        return cartMapper.updateCart(cart);
    }
    public Integer addOrder(List<Integer> cartIds, Integer userId) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfoMapper.addOrder(orderInfo);
        int orderId = orderInfoMapper.selectCount();
        List<OrderItem> orderItems = new ArrayList<>();
        for (Integer id :
                cartIds) {
            Cart c = cartMapper.selectCartByCartId(id);

            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(orderId);
            orderItem.setDrugId(c.getDrugId());
            orderItem.setQuantity(c.getNum());
            orderItems.add(orderItem);
        }

        return orderItemService.addOrderItems(orderItems);
    }
}
